import { handleActions } from 'redux-actions'
import { INIT_USERINFO_TYPE, UPDATE_USERINFO_TYPE, UPDATE_USERINFO_TOKEN_TYPE } from '../types/userinfo'
import DeviceStorage from 'src/utils/DeviceStorage'
import { isEmptyObjectFn } from 'src/utils/JSTypeUtil'

const Schema = {
  role: null, // company=>B || personal=>C
  B: {},
  C: {}
}
export default handleActions(
  {
    [INIT_USERINFO_TYPE] (state, action) {
      const userinfo = {
        ...Schema,
        role: state.role
      }
      DeviceStorage.set('userinfo', userinfo)
      return {
        ...userinfo
      }
    },
    [UPDATE_USERINFO_TYPE] (state, action) {
      if (isEmptyObjectFn(action.payload) || action.error) {
        return state
      } else {
        const userinfo = {
          ...state,
          ...action.payload
        }
        DeviceStorage.set('userinfo', userinfo)
        return {
          ...userinfo
        }
      }
    },
    [UPDATE_USERINFO_TOKEN_TYPE] (state, action) {
      if (isEmptyObjectFn(action.payload) || action.error) {
        const { code } = action.payload
        if (code && code !== 200) { // token失效
          const userinfo = {
            ...Schema,
            role: state.role
          }
          DeviceStorage.set('userinfo', userinfo)
          return {
            ...userinfo
          }
        } else {
          return state
        }
      } else {
        const userinfo = {
          ...state,
          ...action.payload
        }
        DeviceStorage.set('userinfo', userinfo)
        return {
          ...userinfo
        }
      }
    }
  },
  { ...Schema }
)
